package com.global.variable.common.web.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.lang.Nullable;

/**
 * company 重庆庆云石油工程技术有限责任公司
 * FileName RedisObjectSerializer
 * Package com.basic.management.logic.config.redis
 * Description redis序列化对象
 * author zjh
 * create 2018-10-17 上午 11:13
 * version V1.0
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {


    private Converter<Object, byte[]> serializer = new SerializingConverter();

    private Converter<byte[], Object> deserializer = new DeserializingConverter();

    static final byte[] EMPTY_ARRAY = new byte[0];

    @Override
    public byte[] serialize(@Nullable Object o) {
        if (o == null) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(o);
        } catch (Exception e) {
            return EMPTY_ARRAY;
        }

    }

    @Override
    public Object deserialize(@Nullable byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deserializer.convert(bytes);
        } catch (Exception e) {
            throw new RuntimeException("Cannot deserialize");
        }

    }

    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }
}
